<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="属性名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入属性名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="规格类型" prop="typeId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="请选择规格类型"
          clearable
          filterable
        >
          <el-option
            v-for="specType in specTypeList"
            :key="specType.id"
            :label="specType.name"
            :value="specType.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:productSpec:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:productSpec:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:productSpec:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['product:productSpec:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productSpecList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="属性名称" align="center" prop="name" />
      <el-table-column label="规格类型" align="center" prop="typeId" />
      <el-table-column label="可选值" align="center" prop="valuesJson" />
      <!-- 列表显示转换为是/否 -->
      <el-table-column label="是否影响SKU生成" align="center" prop="isSku">
        <template #default="scope">
          <span>{{
            scope.row.isSku === 1 || scope.row.isSku === "1" ? "是" : "否"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="是否允许自定义输入"
        align="center"
        prop="isCustom"
      >
        <template #default="scope">
          <span>{{
            scope.row.isCustom === 1 || scope.row.isCustom === "1" ? "是" : "否"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="排序权重" align="center" prop="sort" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        width="200px"
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:productSpec:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:productSpec:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规格属性对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="productSpecRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="属性名称" style="width: 350px" prop="name">
          <el-input v-model="form.name" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="规格类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择规格类型"
            clearable
            filterable
          >
            <el-option
              v-for="specType in specTypeList"
              :key="specType.id"
              :label="specType.name"
              :value="specType.id"
            />
          </el-select>
        </el-form-item>
        <!-- 表单改为单选按钮组 -->
        <el-form-item label="是否影响SKU生成" label-width="140px" prop="isSku">
          <el-radio-group v-model="form.isSku">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许自定义" label-width="140px" prop="isCustom">
          <el-radio-group v-model="form.isCustom">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="单位" style="width: 350px" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="排序权重" style="width: 350px" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序权重" />
        </el-form-item>
        <el-form-item label="可选值" style="width: 350px" prop="valuesJson">
          <el-input
            v-model="form.valuesJson"
            placeholder="请输入JSON格式的可选值"
            type="textarea"
            rows="3"
          />
          <div class="el-form-item__help">
            示例：["红色","蓝色"]（请使用英文双引号）
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductSpec">
import {
  listProductSpec,
  getProductSpec,
  delProductSpec,
  addProductSpec,
  updateProductSpec,
} from "@/api/product/productSpec";
import { listSpecType } from "@/api/product/specType";
import { onMounted } from "vue";
const { proxy } = getCurrentInstance();

const productSpecList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const specTypeList = ref([]);
const data = reactive({
  form: {
    // 初始化默认值为0（否）
    isSku: "0",
    isCustom: "0",
    valuesJson: "", // 可选值默认为空字符串
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    typeId: null,
    valuesJson: null,
    isSku: null,
    isCustom: null,
    unit: null,
    sort: null,
  },
  rules: {
    name: [{ required: true, message: "属性名称不能为空", trigger: "blur" }],
    typeId: [
      { required: true, message: "规格类型ID不能为空", trigger: "blur" },
    ],
    // 新增必选验证
    isSku: [
      { required: true, message: "请选择是否影响SKU生成", trigger: "change" },
    ],
    isCustom: [
      {
        required: true,
        message: "请选择是否允许自定义输入",
        trigger: "change",
      },
    ],
    valuesJson: [
      {
        pattern: /^\[\s*"[^"]+"(\s*,\s*"[^"]+")*\s*\]$/,
        message: '请输入正确的JSON格式（如["值1","值2"]）',
        trigger: "blur",
        required: false, // 设为true则表示必填
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品规格属性列表 */
function getList() {
  loading.value = true;
  listProductSpec(queryParams.value).then((response) => {
    productSpecList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询规格类型列表 */
function getSpecTypeList() {
  listSpecType({ pageSize: 999 }).then((response) => {
    specTypeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    typeId: null,
    valuesJson: null,
    isSku: "0", // 重置默认值为否
    isCustom: "0", // 重置默认值为否
    unit: null,
    sort: null,
  };
  proxy.resetForm("productSpecRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品规格属性";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]; // 修复数组取值问题
  getProductSpec(_id).then((response) => {
    // 确保状态值为字符串类型，与单选按钮组匹配
    const data = response.data;
    form.value = {
      ...data,
      isSku: data.isSku.toString(),
      isCustom: data.isCustom.toString(),
    };
    open.value = true;
    title.value = "修改商品规格属性";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productSpecRef"].validate((valid) => {
    if (valid) {
      // 提交时保持字符串类型或转为数字，根据后端接口要求调整
      const submitData = {
        ...form.value,
        // 如需数字类型可在此转换：
        // isSku: Number(form.value.isSku),
        // isCustom: Number(form.value.isCustom)
      };

      if (form.value.id != null) {
        updateProductSpec(submitData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProductSpec(submitData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row ? [row.id] : ids.value; // 修复删除参数格式
  proxy.$modal
    .confirm(`是否确认删除商品规格属性"${row ? row.name : _ids}"？`)
    .then(function () {
      return delProductSpec(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "product/productSpec/export",
    {
      ...queryParams.value,
    },
    `productSpec_${new Date().getTime()}.xlsx`
  );
}

onMounted(() => {
  getList();
  getSpecTypeList();
});
</script>
